const app = getApp()
const util = require('../../../../../../utils/util.js');
const api = require('../../../../../../config/api.js');
Page({
  data: {
    //辅助数据  nowDate 当前的时间  showOccupied 不可选日期弹窗控制  showDissolve 解散弹窗控制  showFunctionPop 功能面板
    auxiliary: { "nowDate": '', 'showOccupied': false, "showDissolve": false, "showFunctionPop": false, "screenInfoSelectIndex": "", "showFunctionPopIndex": "", "showMoveOut": false,"showSetPlace":false},
    // 不能选择的日期
    themeNotSelectTime: [],
    // 主题组以及主题信息（页面加载时的数据）
    groupInfo: {},
    // 修改后的数据
    groupInfo2: {},
  },
  onLoad: function (options) {
    var _this = this;
    _this.setData({
      ["auxiliary.circleid"]: options.circleid,
      ["auxiliary.groupid"]: options.groupid,
      ["auxiliary.nowDate"]: util.getDateStr(new Date(), 0)
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this;
    _this.getGroupInfo();
    _this.getThemeNotSelectTime();
  },
  /**
   * 查询不可选的日期（只过滤主题、以及主题中已有关联主题组的）
   */
  getThemeNotSelectTime: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.circleid = _this.data.auxiliary.circleid;
        data.access_token = res.access_token;
        util.post(api.Interest_GetThemeNotSelectTimeApi, data).then(function (res) {
          if (res.code == 200) {
            _this.setData({
              themeNotSelectTime: res.result
            })
          }
        })
      })
    }
  },
  /**
   * 获取分组信息
   */
  getGroupInfo: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.circleid = _this.data.auxiliary.circleid;
        data.groupid = _this.data.auxiliary.groupid;
        data.access_token = res.access_token;
        util.post(api.Interest_GetGroupInfoApi, data).then(function (res) {
          if (res.code == 200) {
            if(res.result == null){
              wx.navigateBack({
                delta: 1
              });
            }
            var themeGroup = res.result.themeGroup;
            var sortType = themeGroup.sortType;
            var screenInfo = res.result.screenInfo;
            var placeDate = themeGroup.sortTime;
            if (placeDate != null && String(placeDate).length > 0) {
              placeDate = util.formatDate(new Date(placeDate));
            } else {
              placeDate = _this.data.auxiliary.nowDate;
            }
            var groupInfo2 = {};
            groupInfo2.sortType = sortType;
            groupInfo2.placeDate = placeDate;
            groupInfo2.screenInfo = screenInfo;
            _this.setData({
              groupInfo: res.result,
              groupInfo2: groupInfo2
            })
            _this.jsOrderTheme();
          }
        })
      })
    }
  },

  /**
   * 选择排序类型
   */
  selectSortType: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var sortType = _this.data.groupInfo2.sortType;
    _this.setData({
      ["groupInfo2.sortType"]: index
    })
    if (sortType != index) {
      _this.jsOrderTheme();
    }
  },

  /**
   * 计算排序主题或主题组
   */
  jsOrderTheme: function () {
    var _this = this;
    var sortType = _this.data.groupInfo2.sortType;

    var screenInfoList = _this.data.groupInfo.screenInfoList;
    var screenInfo = _this.data.groupInfo.screenInfo;
    var ySortType = _this.data.groupInfo.themeGroup.sortType;
    var themeType = _this.data.groupInfo.ordInterest.themeType;
    var screenInfoList2 = [];
    if ((sortType == 1 || sortType == 2) && ySortType == sortType) {
      screenInfoList2.push(screenInfo);
    } else if (screenInfo.type == 1 && sortType == 1 && themeType == 1){
      if (!(screenInfo.groupid != null && screenInfo.groupid > 0)) {
        screenInfoList2.push(screenInfo);
      }
    }
    for (var i = 0; i < screenInfoList.length; i++) {
      var isAdd = true;
      var type = screenInfoList[i].type;
      var dataid = screenInfoList[i].dataid;
      var groupid = screenInfoList[i].groupid;
      if (type == 1 && themeType == 1 && sortType == 1) {
        // 循环的是主题、并且是经典模式、并且是排在前的，需要过滤主题中带有主题组的
        if (groupid != null && groupid > 0) {
          isAdd = false;
        }
      }
      if (themeType == 1 && sortType == 2) {
        // 经典模式，排在谁后面
        // 需要过滤前后只相隔一天的主题、或者主题组
        var time1 = screenInfoList[i].time;
        if (i > 0 && i < screenInfoList.length - 1) {
          var time2 = screenInfoList[i + 1].time;
          var day = time.calculateDifferDay(time1, time2);
          if (day <= 1) {
            isAdd = false;
          }
        }
      }
      if (screenInfo.dataid == dataid && type == screenInfo.type){
        isAdd = false;
      }
      
      if (isAdd) {
        screenInfoList2.push(screenInfoList[i]);
      }
    }
    _this.setData({
      ["groupInfo2.screenInfoList2"]: screenInfoList2,
    })
    if (screenInfoList2.length > 0) {
      _this.setData({
        ["groupInfo2.screenInfo"]: screenInfoList2[0],
        ["auxiliary.screenInfoSelectIndex"]: 0
      })
    } else {
      _this.setData({
        ["groupInfo2.screenInfo"]: {},
        ["auxiliary.screenInfoSelectIndex"]: ""
      })
    }
  },

  /**
   * 打开已选日期面板
   */
  openOccupied: function () {
    var _this = this;
    _this.setData({
      ["auxiliary.showOccupied"]: true
    })
  },
  /**
   * 打开排序面板
   */
  openSetPlace: function () {
    var _this = this;
    _this.setData({
      ["auxiliary.showSetPlace"]: true
    })
  },
  /**
  * 关闭排序面板
  */
  closeSetPlace: function () {
    var _this = this;
    _this.setData({
      ["auxiliary.showSetPlace"]: false
    })
  },
  /**
   * 打开解散面板
   */
  openDissolve: function () {
    var _this = this;
    _this.setData({
      ["auxiliary.showDissolve"]: true
    })
  },
  /**
   * 关闭所有弹窗
   */
  closeMC: function () {
    var _this = this;
    _this.setData({
      ["auxiliary.showOccupied"]: false,
      ["auxiliary.showDissolve"]: false,
      ["auxiliary.showFunctionPop"]: false,
      ["auxiliary.showMoveOut"]: false,
      ["auxiliary.showFunctionPopIndex"]: "",
    })
  },
  /**
   * 选中排位的目标
   */
  selectPlaceTarget: function (e) {
    var _this = this
    var index = e.detail.value;
    var arr = _this.data.groupInfo2.screenInfoList2;
    _this.setData({
      ["groupInfo2.screenInfo"]: arr[index]
    })
  },
  /**
   * 选中排位的时间
   */
  selectPlaceDate: function (e) {
    var _this = this;
    var date = e.detail.value;
    var themeNotSelectTime = _this.data.themeNotSelectTime;
    for (var i = 0; i < themeNotSelectTime.length; i++) {
      if (themeNotSelectTime[i] == date) {
        util.showToast("不能选择" + date, "none");
        return;
      }
    }
    _this.setData({
      ["groupInfo2.placeDate"]: date
    })
  },
  /**
   * 添加主题
   */
  gotoAdd: function () {
    var _this = this
    wx.navigateTo({
      url: '../setThemeGroup/setThemeGroup?addTheme=1&circleid=' + _this.data.auxiliary.circleid + "&groupid=" + _this.data.auxiliary.groupid,
    })
  },

  /**
   * 允许成员一天闯多关
   */
  isCheckpointDayChange: function () {
    wx.showLoading({
      title: '请求中',
    })
    var _this = this;
    var circleid = _this.data.auxiliary.circleid;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.circleid = circleid;
        data.openid = openid;
        data.access_token = res.access_token;
        data.type = 2;// 修改类型：1修改总的  2修改单个组
        data.groupid = _this.data.auxiliary.groupid;
        var isCheckpointDay = _this.data.groupInfo.themeGroup.isCheckpointDay;
        if (isCheckpointDay == 1) {
          // 关闭
          data.isCheckpointDay = 0;
          data.isCheckpoint = 0;
        } else {
          data.isCheckpointDay = 1;
          data.isCheckpoint = 0;
        }
        _this.updateCheckpointQuery(data);
      })
    }
  },

  /**
   * 允许成员任意闯多关
   */
  isCheckpointChange: function () {
    wx.showLoading({
      title: '请求中',
    })
    var _this = this;
    var circleid = _this.data.auxiliary.circleid;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.circleid = circleid;
        data.openid = openid;
        data.access_token = res.access_token;
        data.isCheckpointDay = _this.data.groupInfo.themeGroup.isCheckpointDay;
        data.type = 2;// 修改类型：1修改总的  2修改单个组
        data.groupid = _this.data.auxiliary.groupid;
        var isCheckpoint = _this.data.groupInfo.themeGroup.isCheckpoint;
        if (isCheckpoint == 1) {
          // 关闭
          data.isCheckpoint = 0;
        } else {
          data.isCheckpoint = 1;
        }
        _this.updateCheckpointQuery(data);
      })
    }
  },

  /**
   * 修改参加主题设置
   */
  updateCheckpointQuery: function (data) {
    var _this = this;
    util.post(api.Interest_UpdateCheckpointApi, data).then(function (res) {
      wx.hideLoading();
      if (res.code == 200) {
        _this.setData({
          ["groupInfo.themeGroup.isCheckpoint"]: data.isCheckpoint,
          ["groupInfo.themeGroup.isCheckpointDay"]: data.isCheckpointDay
        })
      } else {
        util.showToast(res.message, "none");
      }
    })
  },

  /**
   * 主题移动
   */
  themeMobile: function (e) {
    wx.showLoading({
      title: '请求中',
    })
    var _this = this;
    var themeList = _this.data.groupInfo.themeList;
    var index = e.currentTarget.dataset.index;
    var circleid = _this.data.auxiliary.circleid;
    var type = e.currentTarget.dataset.type;
    var openid = app.globalData.logininfo.openid;
    var themeid = themeList[index].id;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.themeid = themeid;
        data.type = type;
        data.circleid = circleid;
        data.access_token = res.access_token;
        util.post(api.Interest_ThemeMobileApi, data).then(function (res) {
          wx.hideLoading();
          if (res.code == 200) {
            _this.getGroupInfo();
          } else {
            util.showToast(res.message, "none");
          }
        })
      })
    }
  },

  /**
   * 进入主题编辑页面
   */
  navigateToMakeTheme: function (e) {
    var _this = this;
    var circleid = _this.data.auxiliary.circleid;
    var index = e.currentTarget.dataset.index;
    if (index != null && String(index).length > 0) {
      var copy = e.currentTarget.dataset.copy;
      var themeList = _this.data.groupInfo.themeList;
      var themeid = themeList[index].id;
      if (copy == "copy") {
        wx.navigateTo({
          url: '../../makeTheme/makeTheme?o_type=copy&themeid=' + themeid + '&circleid=' + circleid + '&type=' + _this.data.groupInfo.ordInterest.themeType,
        })
      } else {
        wx.navigateTo({
          url: '../../makeTheme/makeTheme?o_type=update&themeid=' + themeid + '&circleid=' + circleid + '&type=' + _this.data.groupInfo.ordInterest.themeType,
        })
      }
    } else {
      wx.navigateTo({
        url: '../../makeTheme/makeTheme?o_type=create&themeid=&circleid=' + circleid + '&type=' + _this.data.groupInfo.ordInterest.themeType,
      })
    }
  },

  /**
   * 打开功能面板
   */
  openFunctionPop: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    this.setData({
      ["auxiliary.showFunctionPop"]: true,
      ["auxiliary.showFunctionPopIndex"]: index,
    })
  },

  /**
   * 主题设置页
   */
  navigateToThemeSet: function () {
    var _this = this;
    var index = _this.data.auxiliary.showFunctionPopIndex;
    var themeList = _this.data.groupInfo.themeList;
    var themeid = themeList[index].id;
    var circleid = _this.data.auxiliary.circleid;
    wx.navigateTo({
      url: '../../makeTheme/themeSet/themeSet?circleid=' + circleid + '&themeid=' + themeid,
    })
  },

  /**
   * 删除主题
   */
  deleteTheme: function () {
    var _this = this;
    var index = _this.data.auxiliary.showFunctionPopIndex;
    var themeList = _this.data.groupInfo.themeList;
    var themeid = themeList[index].id;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.themeid = themeid;
        data.openid = openid;
        data.access_token = res.access_token;
        util.post(api.Interest_DeleteThemeApi, data).then(function (res) {
          if (res.code == 200) {
            _this.closeMC();
            util.showToast("删除成功", "success");
            _this.getGroupInfo();
          } else {
            util.showToast(res.message, "none");
          }
        })
      })
    }
  },

  /**
   * 显示移出本组的提示框
   */
  showMoveOut: function(){
    var _this = this;
    _this.setData({
      ["auxiliary.showMoveOut"]: true
    })
  },

  /**
   * 确定移出本组
   */
  themeMoveOut: function(){
    var _this = this;
    var index = _this.data.auxiliary.showFunctionPopIndex;
    var themeList = _this.data.groupInfo.themeList;
    var themeid = themeList[index].id;
    var circleid = _this.data.auxiliary.circleid;
    var groupid = _this.data.auxiliary.groupid;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.themeid = themeid;
        data.openid = openid;
        data.groupid = groupid;
        data.access_token = res.access_token;
        util.post(api.Interest_ThemeMoveOutApi, data).then(function (res) {
          if (res.code == 200) {
            _this.closeMC();
            util.showToast("移出成功", "success");
            _this.getGroupInfo();
          } else {
            util.showToast(res.message, "none");
          }
        })
      })
    }
  },

  /**
   * 确定移出本组
   */
  themeGroupMoveOut: function () {
    var _this = this;
    var circleid = _this.data.auxiliary.circleid;
    var groupid = _this.data.auxiliary.groupid;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.groupid = groupid;
        data.access_token = res.access_token;
        util.post(api.Interest_ThemeGroupMoveOutApi, data).then(function (res) {
          if (res.code == 200) {
            wx.navigateBack({
              delta: 1
            });
          } else {
            util.showToast(res.message, "none");
          }
        })
      })
    }
  },

  /**
   * 修改主题组排序
   */
  updateThemeGroupSort: function(){
    var _this = this;
    _this.closeSetPlace();
    var sortType = _this.data.groupInfo2.sortType;
    var placeDate = _this.data.groupInfo2.placeDate;
    var screenInfo = _this.data.groupInfo2.screenInfo;
    
    var oldSortType = _this.data.groupInfo.themeGroup.sortType;
    var oldScreenInfo = _this.data.groupInfo.screenInfo;
    var oldPlaceDate = _this.data.groupInfo.themeGroup.sortTime;
    if (((sortType == 1 || sortType == 2) && screenInfo != null && JSON.stringify(screenInfo) != '{}') || sortType == 3){
      // 需要调用接口修改
      var openid = app.globalData.logininfo.openid;
      if (openid != null && openid != "") {
        wx.showLoading({
          title: '更改中',
        })
        util.post(api.fetchToken()).then(function (res) {
          if (res.access_token != '') {
            return Promise.resolve({
              access_token: res.access_token
            });
          }
        }).then(function (res) {
          var data = {};
          data.openid = openid;
          data.sortType = sortType;
          data.placeDate = placeDate;
          data.screenInfo = screenInfo;
          data.circleid = _this.data.auxiliary.circleid;
          data.groupid = _this.data.auxiliary.groupid;
          data.access_token = res.access_token;
          util.post(api.Interest_UpdateThemeGroupSortApi, data).then(function (res) {
            if (res.code == 200) {
              _this.getGroupInfo();
              _this.getThemeNotSelectTime();
            }else{
              util.showToast(res.message, "none");
            }
            wx.hideLoading();
          })
        })
      }
    }
  },
})